package com.aliyun.messagemgt.application.service.Impl.push.newsms;

import com.alibaba.csb.sdk.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.messagemgt.application.service.MsgPushChannel;
import com.aliyun.messagemgt.common.dto.send.*;
import com.aliyun.messagemgt.dto.vo.MessageSendVO;
import com.aliyun.messagemgt.common.enums.ChannelTypeEnum;
import com.taobao.api.ApiException;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 海南项目需要对接新短信渠道
 *
 * @author byp
 * @date 2020/8/24
 */
@Service
public class NewSmsPushChannel implements MsgPushChannel {

    @Value("${new.sms.csbUrl}")
    private String csbUrl;
    @Value("${new.sms.apiName}")
    private String apiName;
    @Value("${new.sms.apiVersion}")
    private String apiVersion;
    @Value("${new.sms.ak}")
    private String ak;
    @Value("${new.sms.sk}")
    private String sk;

    @Value("${new.sms.params.appCode}")
    private String appCode;
    @Value("${new.sms.params.topicCode}")
    private String topicCode;
    @Value("${new.sms.params.channelCode}")
    private String channelCode;

    private static Logger logger = LoggerFactory.getLogger(NewSmsPushChannel.class);

    @Override
    public Integer getChannelType() {
        return ChannelTypeEnum.NEW_SMS_CHANNEL.getType();
    }

    @Override
    public void push(PushChannelInfo pushChannelInfo, MsgRecordVO msgRecordVO) throws ApiException {
        //接口文档中只有一个手机号。那这里暂时只支持一个手机号一次
        List<Receiver> receiverList = msgRecordVO.getReceivers();
        if (CollectionUtils.isEmpty(receiverList)) {
            logger.info("接收人为空，或短时间内重复消息抑制");
            return;
        }
        String phone = receiverList.get(0).getReceiverId();
        //接口文档中：userid;phone
        phone = phone + ";" + phone;

        MessageSendVO messageSendVO = new MessageSendVO();
        messageSendVO.setAppCode(appCode)
                .setChannelCode(channelCode)
                .setMessageTypeCode(msgRecordVO.getMessageType())
                .setTopicCode(topicCode)
                .setReceiverUidType("USERID-PHONE")
                .setReceiverUid(phone);
        List<MsgBody> contents = msgRecordVO.getContents();
        String body = contents.get(0).getContent();
        JSONObject object = JSONObject.parseObject(body);
        List<MessageSendVO.Variable> variables = new ArrayList<>();
        MessageSendVO.Variable variable;
        for (Map.Entry<String, Object> entry : object.entrySet()) {
            variable = new MessageSendVO.Variable();
            variable.setKey(entry.getKey());
            variable.setValue((String) entry.getValue());
            variables.add(variable);
        }
        messageSendVO.setVariables(variables);
        logger.info("新短信渠道发送请求参数：{}", messageSendVO.toString());
        JSONObject params = JSONObject.parseObject(JSONObject.toJSONString(messageSendVO));
        JSONObject msg = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(params);
        msg.put("messages", jsonArray);
        logger.info("新短信渠道发送请求json参数：{}", msg.toJSONString());

        ContentBody cb = new ContentBody(msg.toJSONString());
        HttpParameters.Builder builder = build();
        builder.contentBody(cb);
        List<MsgMiddleResult> pushResult = msgRecordVO.getResults();
        //进行调用，返回结果
        try {
            HttpReturn ret = HttpCaller.invokeReturn(builder.build());
            if (ret.httpCode == 200) {
                String result = ret.getResponseStr();
                JSONObject res = JSONObject.parseObject(result);
                logger.info("返回结果为：{}", res);
                if (res.getBoolean("success")) {
                    logger.info("短信发送成功");
                    MsgMiddleResult msgMiddleResult = new MsgMiddleResult().setPushResultCode(1)
                            .setPushResultDescription("推送成功").setReceivers(msgRecordVO.getReceivers());
                    pushResult.add(msgMiddleResult);
                } else {
                    String message = res.getString("message");
                    logger.info("失败原因；{}", message);
                    MsgMiddleResult msgMiddleResult = new MsgMiddleResult().setPushResultCode(2)
                            .setPushResultDescription(message).setReceivers(msgRecordVO.getReceivers());
                    pushResult.add(msgMiddleResult);
                }
            } else {
                logger.info("返回状态不为200，返回状态为:{}", ret.httpCode);
                MsgMiddleResult msgMiddleResult = new MsgMiddleResult().setPushResultCode(2)
                        .setPushResultDescription("调用失败").setReceivers(msgRecordVO.getReceivers());
                pushResult.add(msgMiddleResult);
            }

        } catch (HttpCallerException e) {
            logger.info("调用接口异常");
            MsgMiddleResult msgMiddleResult = new MsgMiddleResult().setPushResultCode(2)
                    .setPushResultDescription("调用接口异常").setReceivers(msgRecordVO.getReceivers());
            pushResult.add(msgMiddleResult);
        }
    }

    /**
     * 创建build
     *
     * @return builder
     */
    private HttpParameters.Builder build() {
        HttpParameters.Builder builder = HttpParameters.newBuilder();
        builder.requestURL(csbUrl)
                .api(apiName)
                .version(apiVersion)
                .method("post")
                .accessKey(ak)
                .secretKey(sk);

        return builder;
    }
}
